extends Control

@export var max_length: float = 360.0
@export var dash_len: float = 10.0
@export var dash_gap: float = 14.0
@export var main_width: float = 2.0
@export var edge_width: float = 1.0
@export var sector_step: float = 28.0
@export var base_alpha: float = 0.08
@export var inner_blank_radius: float = 40.0  # 玩家身边保留一圈不渲染，减小遮挡
@export var max_redraw_hz: float = 0.0  # 0 表示跟随 Engine.max_fps，可视时自动匹配帧率
@export var snap_to_pixels: bool = true  # 对绘制起点像素对齐，减少抖动

var aim_direction: Vector2 = Vector2.ZERO
var spread_deg: float = 8.0
var player: Node2D
var _redraw_accum: float = 0.0

func _ready():
	mouse_filter = Control.MOUSE_FILTER_IGNORE
	set_process(false)
	visible = false
	# 自动寻找玩家
	player = get_tree().get_first_node_in_group("player")
	z_index = -1  # 降低遮挡优先级

func show_aim(direction: Vector2, spread_in_deg: float):
	aim_direction = direction.normalized() if direction.length() > 0.001 else Vector2.ZERO
	spread_deg = spread_in_deg
	visible = aim_direction != Vector2.ZERO
	set_process(visible)
	queue_redraw()

func hide_aim():
	visible = false
	set_process(false)
	queue_redraw()

func _process(_dt):
	# 可视时按频率上限重绘，避免每帧重绘带来的额外消耗
	if visible:
		_redraw_accum += _dt
		var target_fps: float = float(Engine.max_fps) if Engine.max_fps > 0 else 60.0
		var cap_hz: float = max_redraw_hz if max_redraw_hz > 0.0 else target_fps
		var interval: float = 1.0 / max(1.0, cap_hz)
		if _redraw_accum >= interval:
			_redraw_accum = 0.0
			queue_redraw()

func _draw():
	if not visible or not player:
		return
	
	# 跨画布精确换算：把玩家的“带画布全局变换”转换到本控件局部
	var player_canvas_xform: Transform2D = player.get_global_transform_with_canvas()
	var my_canvas_inv: Transform2D = get_global_transform_with_canvas().affine_inverse()
	var o: Vector2 = my_canvas_inv * player_canvas_xform.origin
	if snap_to_pixels:
		o = Vector2(round(o.x), round(o.y))
	
	var center_dir: Vector2 = aim_direction
	var center_angle: float = center_dir.angle()
	var half_spread: float = deg_to_rad(spread_deg) * 0.5
	var left_angle: float = center_angle - half_spread
	var right_angle: float = center_angle + half_spread
	var left_dir: Vector2 = Vector2.RIGHT.rotated(left_angle)
	var right_dir: Vector2 = Vector2.RIGHT.rotated(right_angle)
	
	# 扇形渐隐覆盖：由近到远，越远越透明（保留内圈空白）
	var r: float = max(sector_step, inner_blank_radius + sector_step)
	while r <= max_length:
		var alpha: float = base_alpha * (1.0 - (r / max_length))
		if alpha > 0.01:
			_draw_sector_ring(o, center_angle, half_spread, max(inner_blank_radius, r - sector_step), r, Color(1,1,1,alpha))
		r += sector_step
	
	# 长虚线（主方向），从内圈边缘开始
	var t: float = inner_blank_radius
	while t < max_length:
		var seg_len: float = min(dash_len, max_length - t)
		var p1: Vector2 = o + center_dir * t
		var p2: Vector2 = o + center_dir * (t + seg_len)
		draw_line(p1, p2, Color(1,1,1,0.8), main_width)
		t += dash_len + dash_gap
	
	# 两条细实线（散布边界）
	var el: Vector2 = o + left_dir * max_length
	var er: Vector2 = o + right_dir * max_length
	draw_line(o + left_dir * inner_blank_radius, el, Color(1,1,1,0.5), edge_width)
	draw_line(o + right_dir * inner_blank_radius, er, Color(1,1,1,0.5), edge_width)

func _draw_sector_ring(center_pt: Vector2, center_angle: float, half_spread: float, r0: float, r1: float, color: Color):
	# 画一个扇形环（近似），外圈和内圈顶点拼接
	var pts: PackedVector2Array = []
	var steps = max(6, int((half_spread * 2.0) * 12.0))
	for i in range(steps + 1):
		var t = float(i) / float(steps)
		var a = center_angle - half_spread + (half_spread * 2.0) * t
		pts.append(center_pt + Vector2.RIGHT.rotated(a) * r1)
	for i in range(steps, -1, -1):
		var t = float(i) / float(steps)
		var a = center_angle - half_spread + (half_spread * 2.0) * t
		pts.append(center_pt + Vector2.RIGHT.rotated(a) * r0)
	if pts.size() >= 3:
		draw_colored_polygon(pts, color)
